package com.situ.skymall.admin.api.controller;

import com.situ.admin.model.Account;
import com.situ.admin.model.Admin;
import com.situ.admin.service.AdminService;
import com.situ.utils.JsonResult;
import com.situ.utils.JwtUtils;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/admin_login")
public class LoginController {

    private AdminService adminService;
    private RedisTemplate<Object, Object> redisTemplate;
    private final StrongPasswordEncryptor PE = new StrongPasswordEncryptor();

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    /**
     * 管理员登录
     */
    @PostMapping()
    public JsonResult<?> login(@RequestBody Account account) {
        try {
            // 验证码校验
            String correct = (String) redisTemplate.opsForValue().get("captcha-"+account.getCaptchaId());
            System.out.println("Redis中的验证码: " + correct);
            System.out.println("管理员输入的验证码: " + account.getCaptcha());
            if (correct == null) {
                return JsonResult.fail("验证码已过期");
            }
            if (!correct.equalsIgnoreCase(account.getCaptcha())) {
                return JsonResult.fail("验证码错误");
            }

            // 验证成功后，立即删除验证码，防止重复使用
            redisTemplate.delete("captcha-" + account.getCaptchaId());

            // 管理员名密码校验
            Admin admin = adminService.findByAdminname(account.getAdminname());
            if (admin == null){
                return JsonResult.fail("管理员不存在");
            }

            boolean pass = PE.checkPassword(account.getPassword(), admin.getPassword());
            if (!pass) {
                return JsonResult.fail("密码不正确");
            }

            // 检查管理员状态
            if (admin.getStatus() != 1) {
                return JsonResult.fail("管理员已被禁用");
            }

            //生成带有 scope 的JWT
            Map<String, Object> claims = new HashMap<>();
            // 生成时转为字符串
            claims.put("id", String.valueOf(admin.getId()));
            claims.put("name", admin.getAdminname());
            claims.put("isSuper", admin.getIsSuper());
            claims.put("scope", "ADMIN"); // 添加角色范围声明

            String jwt = JwtUtils.createJwt(UUID.randomUUID().toString(), admin.getAdminname(),
                    claims, LocalDateTime.now().plusHours(2), jwtSecret);

            return JsonResult.success(jwt);
        } catch (Exception e) {
            System.err.println("登录时发生严重错误，详细信息如下:");
            e.printStackTrace();

            // 返回给前端的依然是通用错误信息，但我们可以在后端日志中看到具体原因
            return JsonResult.fail(500, "登录过程中发生错误，请联系管理员");
        }
    }




    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public void captcha(@RequestParam(required = true) String id,
                        HttpServletResponse resp,
                        HttpServletRequest req) throws IOException {
        try {
            // 参数校验
            if (id == null || id.trim().isEmpty()) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "验证码ID不能为空");
                return;
            }

            SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);

            // 设置响应头
            resp.setContentType("image/gif");
            resp.setHeader("Pragma", "No-cache");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setDateHeader("Expires", 0);

            // 保存验证码到Redis
            String captchaText = captcha.text().toLowerCase();
            redisTemplate.opsForValue().set("captcha-" + id,
                    captchaText,
                    Duration.ofMinutes(3));

            // 输出验证码图片
            captcha.out(resp.getOutputStream());

        } catch (Exception e) {
            System.err.println("生成验证码时发生错误，ID: " + id);
            e.printStackTrace();

            // 设置错误响应
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "验证码生成失败");
        }
    }


}
